﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SObject
{
    public partial class Object
    {
        public void AddChild(Object Child)
        {
            if ( Child == this )
            {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.AppendFormat(@"Object ""{0}"" cannot add self as a child.", this.Name);
                throw (new SObject.Exception(stringBuilder.ToString()));
            }

            if (true == this.children.ContainsKey(Child.Name))
            {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.AppendFormat(@"A child with the name ""{0}"" already exists in ""{1}"".", Child.Name, this.CompleteName);
                throw (new SObject.Exception(stringBuilder.ToString()));
            }
            this.children.Add(Child.Name, Child);

            Child.Parent = this;
            Child.Root = this.Root;
            Child.completeName = Object.NameUtility.ConstructCompleteName(this.CompleteName, Child.Name);
        }

        public Object GetChild(string Name)
        {
            if (false == HasChild(Name))
            {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.AppendFormat(@"A child with the name ""{0}"" does not exist in ""{1}"".", Name, this.CompleteName);
                throw (new SObject.Exception(stringBuilder.ToString()));
            }

            return (this.children[Name]);
        }

        public IReadOnlyList<Object> GetChildren()
        {
            return (this.children.Values.ToList<Object>());
        }

        public bool HasChild(string Name)
        {
            return (this.children.ContainsKey(Name));
        }

        public int ChildrenCount
        {
            get { return (this.children.Count); }
        }
    }
}
